<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
    <title>在线音乐服务器</title>

    <!-- 引入Tailwind CSS实现现代UI -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入Font Awesome图标 -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <!-- 配置Tailwind自定义主题 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#6366f1', // 主色调：靛蓝色
                        secondary: '#8b5cf6', // 辅助色：紫色
                        neutral: '#f3f4f6', // 中性色：浅灰
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .bg-gradient-custom {
                background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
            }
            .card-shadow {
                box-shadow: 0 10px 25px -5px rgba(99, 102, 241, 0.1), 0 8px 10px -6px rgba(99, 102, 241, 0.1);
            }
            .input-focus {
                @apply focus:ring-2 focus:ring-primary/50 focus:border-primary focus:outline-none;
            }
            .table-hover-row {
                @apply hover:bg-gray-50 transition-colors;
            }
            .btn-hover-effect {
                @apply hover:shadow-md hover:shadow-primary/20 active:scale-95 transition-all text-base;
            }
        }

        /* 按钮通用效果 */
        button {
            @apply outline-none focus:ring-2 focus:ring-primary/50 focus:ring-offset-2 transition-all;
        }

        /* 播放器主按钮脉冲动画 */
        @keyframes pulse {
            0% { box-shadow: 0 0 0 0 rgba(99, 102, 241, 0.4); }
            70% { box-shadow: 0 0 0 10px rgba(99, 102, 241, 0); }
            100% { box-shadow: 0 0 0 0 rgba(99, 102, 241, 0); }
        }

        .playing .fa-play {
            animation: pulse 2s infinite;
        }

        /* 按钮悬停提升效果 */
        .btn-hover-lift {
            @apply hover:-translate-y-0.5 active:translate-y-0;
        }

        /* 自定义红色阴影 */
        .shadow-red-md {
            box-shadow: 0 4px 15px -3px rgba(244, 63, 94, 0.3), 0 2px 6px -4px rgba(244, 63, 94, 0.3);
        }

        /* 按钮悬停效果增强 */
        #submit1:hover {
            transform: translateY(-1px);
            box-shadow: 0 6px 20px -5px rgba(99, 102, 241, 0.15);
        }

        #delete:hover {
            transform: translateY(-1px);
            background-image: linear-gradient(to bottom right, #f43f5e, #e11d48);
        }

        /* 按钮点击效果 */
        button:active {
            transition-duration: 100ms;
        }

        /* 删除按钮计数标记动画 */
        #delete:hover span:last-child {
            transform: scale(1.05);
        }
    </style>

</head>
<body class="font-inter bg-gray-50 min-h-screen flex flex-col">
<!-- 顶部导航栏 -->
<header class="bg-white shadow-sm sticky top-0 z-10">
    <div class="container mx-auto px-4 py-3 flex items-center justify-between">
        <div class="flex items-center space-x-2">
            <div class="w-10 h-10 rounded-full bg-gradient-custom flex items-center justify-center text-white">
                <i class="fa fa-music"></i>
            </div>
            <h1 class="text-xl font-bold text-gray-800">音乐服务器</h1>
        </div>

        <div class="flex items-center space-x-4">
            <a href="loveMusic.html" class="..." onclick="preservePlayback(event, 'loveMusic.html')">
                <i class="fa fa-heart mr-1"></i>
                <span class="hidden sm:inline">喜欢列表</span>
            </a>
            <a href="upload.html" class="text-gray-600 hover:text-primary transition-colors flex items-center">
                <i class="fa fa-upload mr-1"></i>
                <span class="hidden sm:inline">上传歌曲</span>
            </a>
            <a href="user.html" class="text-gray-600 hover:text-primary transition-colors flex items-center">
                <i class="fa fa-user mr-1"></i>
                <span class="hidden sm:inline">个人中心</span>
            </a>
        </div>
    </div>
</header>

<!-- 主要内容区 -->
<main class="flex-grow container mx-auto px-4 py-8">
    <!-- 标题和搜索区域 -->
    <div class="mb-8">
        <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-gray-800 mb-4">音乐列表</h2>

        <!-- 在适当的位置添加播放次数显示 -->
        <div class="text-sm text-gray-600">
            播放次数: <span id="playCount">0</span>
        </div>


        <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
            <!-- 搜索框 -->
            <div class="flex-grow max-w-md">
                <div class="relative">
                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-gray-400">
                        <i class="fa fa-search"></i>
                    </div>
                    <input
                            type="text"
                            id="exampleInputName2"
                            placeholder="搜索歌曲或歌手..."
                            class="w-full pl-10 pr-4 py-3 rounded-lg border border-gray-300 input-focus transition-all"
                    >
                </div>
            </div>

            <!-- 操作按钮 -->
            <div class="flex items-center space-x-3">
                <!-- 搜索按钮 - 精致玻璃拟态风格 -->
                <button id="submit1" class="px-5 py-2.5 rounded-xl bg-white/80 backdrop-blur-sm border border-white/30 shadow-sm hover:shadow-md text-primary-dark font-medium transition-all duration-300 hover:bg-white hover:border-primary/30 flex items-center group">
                    <div class="w-6 h-6 rounded-full bg-primary/10 group-hover:bg-primary/20 flex items-center justify-center mr-2 transition-all duration-300">
                        <i class="fa fa-search text-primary text-sm"></i>
                    </div>
                    <span>搜索</span>
                </button>

                <!-- 删除选中按钮 - 精致红色渐变带图标动画 -->
                <button id="delete" class="px-5 py-2.5 rounded-xl bg-gradient-to-br from-red-500 to-rose-600 text-white font-medium shadow-sm hover:shadow-red-md transition-all duration-300 flex items-center group active:scale-[0.98]">
                    <div class="w-6 h-6 rounded-full bg-white/20 group-hover:bg-white/30 flex items-center justify-center mr-2 transition-all duration-300">
                        <i class="fa fa-trash text-white text-sm group-hover:scale-110 transition-transform duration-300"></i>
                    </div>
                    <span>删除选中</span>
                    <span class="ml-1.5 px-1.5 py-0.5 bg-white/20 rounded-md text-xs font-normal group-hover:bg-white/30 transition-all duration-300">×<span id="selectedCount">0</span></span>
                </button>
            </div>
        </div>
    </div>

    <!-- 音乐列表 -->
    <div class="bg-white rounded-xl shadow-sm overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead>
                <tr class="bg-gray-50 text-left">
                    <th class="px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">
                        <div class="flex items-center">
                            <input type="checkbox" id="selectAll" class="w-4 h-4 rounded border-gray-300 text-primary focus:ring-primary">
                        </div>
                    </th>
                    <th class="px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">歌名</th>
                    <th class="px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">歌手</th>
                    <th class="px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                </tr>
                </thead>
                <tbody id="info" class="divide-y divide-gray-200">
                <!-- 音乐列表将通过JavaScript动态加载 -->
                </tbody>
            </table>
        </div>

        <!-- 空状态 -->
        <div id="emptyState" class="hidden py-16 text-center">
            <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 text-gray-400 mb-4">
                <i class="fa fa-music text-2xl"></i>
            </div>
            <h3 class="text-lg font-medium text-gray-900 mb-1">暂无音乐</h3>
            <p class="text-gray-500 max-w-md mx-auto">上传一些音乐或者搜索其他歌曲来丰富您的音乐库</p>
            <button class="mt-4 bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg btn-hover-effect" onclick="window.location.href='upload.html'">
                <i class="fa fa-upload mr-2"></i>上传音乐
            </button>
        </div>
    </div>
</main>

<!-- 页脚 -->
<footer class="bg-white border-t border-gray-200 py-6">
    <div class="container mx-auto px-4 text-center text-gray-500 text-sm">
        <p>&copy; 2025 音乐服务器 | 现代音乐体验</p>
    </div>
</footer>

<!-- 音乐播放器 -->
<div id="musicPlayer"
     class="fixed bottom-0 left-0 right-0 bg-white shadow-lg z-50 transform translate-y-full transition-transform duration-300 ease-in-out">
    <div class="container mx-auto px-4">
        <div class="flex items-center justify-between py-3">
            <!-- 歌曲信息部分 -->
            <div class="flex items-center space-x-4 w-1/3">
                <div class="w-12 h-12 rounded bg-gray-200 flex-shrink-0 overflow-hidden">
                    <img id="playerCover" src="https://source.unsplash.com/random/100x100/?music" alt="封面"
                         class="w-full h-full object-cover">
                </div>
                <div>
                    <h4 id="playerTitle" class="font-medium text-dark truncate">歌曲名称</h4>
                    <p id="playerArtist" class="text-sm text-gray-500">歌手名称</p>
                </div>
            </div>

            <!-- 播放控制和进度条部分 -->
            <div class="flex flex-col items-center w-1/3">
                <div class="flex items-center space-x-4 mb-2">
                    <button id="prevBtn" class="text-gray-600 hover:text-primary transition-colors">
                        <i class="fa fa-step-backward"></i>
                    </button>
                    <button id="playBtn"
                            class="w-10 h-10 flex items-center justify-center rounded-full bg-primary text-white hover:bg-primary-dark">
                        <i class="fa fa-play" id="playIcon"></i>
                    </button>
                    <button id="nextBtn" class="text-gray-600 hover:text-primary transition-colors">
                        <i class="fa fa-step-forward"></i>
                    </button>
                </div>
                <div class="w-full flex items-center space-x-3">
                    <span id="currentTime" class="text-xs text-gray-500">0:00</span>
                    <div class="flex-grow h-1.5 bg-gray-200 rounded-full overflow-hidden">
                        <div id="progressBar" class="bg-primary h-full rounded-full" style="width: 0%"></div>
                    </div>
                    <span id="totalTime" class="text-xs text-gray-500">3:45</span>
                </div>
            </div>

            <!-- 音量和其他控制部分 -->
            <div class="flex items-center justify-end space-x-3 w-1/3">
                <button id="volumeBtn" class="text-gray-600 hover:text-primary transition-colors">
                    <i class="fa fa-volume-up"></i>
                </button>
                <div id="volumeControl" class="w-24 h-1.5 bg-gray-200 rounded-full overflow-hidden hidden">
                    <div id="volumeBar" class="bg-primary h-full rounded-full" style="width: 80%"></div>
                </div>
                <span id="volumeDisplay" class="text-xs text-gray-500">80%</span> <!-- 新增音量显示 -->
                <button id="playlistBtn" class="text-gray-600 hover:text-primary transition-colors">
                    <i class="fa fa-list"></i>
                </button>
                <button id="closePlayer" class="text-gray-600 hover:text-red-500 transition-colors">
                    <i class="fa fa-times"></i>
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 引入jQuery -->
<script src="js/jquery-3.1.1.min.js"></script>

<!-- 音乐列表逻辑 (保持原有逻辑不变) -->
<script>
    $(function () {
        load();

        // 全选/取消全选功能
        $("#selectAll").change(function () {
            $("input[type='checkbox']").prop("checked", $(this).prop("checked"));
        });

        // 搜索按钮点击事件
        $("#submit1").click(function () {
            var name = $("#exampleInputName2").val();
            load(name);
        });

        // 删除选中按钮点击事件
        $("#delete").click(function () {
            var id = new Array();
            var i = 0;

            $("input:checkbox").each(function () {
                if ($(this).is(":checked") && $(this).attr("id") !== "selectAll") {
                    id[i] = $(this).attr("id");
                    i++;
                }
            });

            console.log(id);

            if (id.length === 0) {
                alert("请选择要删除的歌曲！");
                return;
            }

            $.ajax({
                url: "/music/deleteSel",
                data: {"id": id},
                dataType: "json",
                type: "post",
                success: function (obj) {
                    if (obj.data == true) {
                        alert("删除成功！");
                        window.location.href = "list.html";
                    } else {
                        alert("删除失败！");
                    }
                }
            });
        });

        // 音量按钮点击事件
        $('#volumeBtn').click(function () {
            $('#volumeControl').toggleClass('hidden');
        });

        // 音量控制条拖动事件
        $('#volumeControl').on('click', function (e) {
            const rect = this.getBoundingClientRect();
            const x = e.clientX - rect.left; // 获取点击位置相对于元素的横坐标
            const width = $(this).width();
            const volume = x / width; // 计算音量百分比

            audio.volume = volume; // 设置音频音量
            $('#volumeBar').css('width', (volume * 100) + '%'); // 更新音量条宽度
            $('#volumeDisplay').text(Math.round(volume * 100) + '%'); // 更新音量显示
        });
    });

    // 加载音乐列表
    function load(musicName) {
        $.ajax({
            url: "/music/findmusic",
            data: {"musicName": musicName},
            type: "GET",
            dataType: "json",
            success: function (obj) {
                console.log(obj);
                var data = obj.data; // 数组

                if (data.length === 0) {
                    $("#info").html("");
                    $("#emptyState").removeClass("hidden");
                    return;
                }

                // 隐藏空状态
                $("#emptyState").addClass("hidden");

                var s = '';
                for (var i = 0; i < data.length; i++) {
                    var musicUrl = data[i].url + ".mp3";
                    console.log(musicUrl);

                    s += '<tr class="table-hover-row">';
                    s += '<td class="px-6 py-4 whitespace-nowrap">';
                    s += '<input id="' + data[i].id + '" type="checkbox" class="w-4 h-4 rounded border-gray-300 text-primary focus:ring-primary">';
                    s += '</td>';
                    s += '<td class="px-6 py-4 whitespace-nowrap">';
                    s += '<div class="flex items-center">';
                    s += '<div class="w-8 h-8 rounded bg-gray-200 flex items-center justify-center mr-3 flex-shrink-0">';
                    s += '<i class="fa fa-music text-gray-400"></i>';
                    s += '</div>';
                    s += '<div>';
                    s += '<div class="font-medium text-gray-900">' + data[i].title + '</div>';
                    s += '</div>';
                    s += '</div>';
                    s += '</td>';
                    s += '<td class="px-6 py-4 whitespace-nowrap text-gray-500">' + data[i].singer + '</td>';
                    // 在load()函数中替换按钮部分的代码
                    s += '<td class="px-6 py-4 whitespace-nowrap">';
                    s += '<div class="flex items-center space-x-2">';
                    // 播放按钮
                    s += '<button title="播放" onclick="startPlayFromList(' + i + ', ' + JSON.stringify(data).replace(/"/g, '&quot;') + ')" class="w-9 h-9 flex items-center justify-center rounded-full bg-primary/10 hover:bg-primary/20 text-primary transition-all duration-200 shadow-sm hover:shadow-md active:scale-95">';
                    s += '<i class="fa fa-play text-xs"></i>';
                    s += '</button>';
                    // 删除按钮
                    s += '<button title="删除" onclick="deleteInfo(' + data[i].id + ')" class="w-9 h-9 flex items-center justify-center rounded-full bg-red-500/10 hover:bg-red-500/20 text-red-500 transition-all duration-200 shadow-sm hover:shadow-md active:scale-95">';
                    s += '<i class="fa fa-trash text-xs"></i>';
                    s += '</button>';
                    // 喜欢按钮
                    s += '<button title="喜欢" onclick="loveInfo(' + data[i].id + ')" class="w-9 h-9 flex items-center justify-center rounded-full bg-green-500/10 hover:bg-green-500/20 text-green-500 transition-all duration-200 shadow-sm hover:shadow-md active:scale-95">';
                    s += '<i class="fa fa-heart text-xs"></i>';
                    s += '</button>';
                    s += '</div>';
                    s += '</td>';
                    s += '</tr>';
                }
                $("#info").html(s);
            }
        });
    }

    // 更新选中计数
    function updateSelectedCount() {
        const count = $("input[type='checkbox']:checked:not(#selectAll)").length;
        $("#selectedCount").text(count);
        if (count > 0) {
            $("#delete").removeClass("opacity-90").addClass("hover:shadow-red-md");
        } else {
            $("#delete").addClass("opacity-90").removeClass("hover:shadow-red-md");
        }
    }
    // 复选框变化时更新计数
    $(document).on("change", "input[type='checkbox']", updateSelectedCount);
    // 初始化计数
    updateSelectedCount();

    // 播放歌曲
    function playerSong(obj) {
        var name = obj.substring(obj.lastIndexOf("=") + 1);
        // obj:播放的音乐的地址  name:播放的音乐的名称，0：播放的开始时间  true:自动播放
        SewisePlayer.toPlay(obj, name, 0, true);

        // 更新播放器UI
        $(".fixed.bottom-0 .font-medium").text(name);
    }

    // 删除歌曲
    function deleteInfo(obj) {
        console.log(obj);
        $.ajax({
            url: "/music/delete",
            type: "POST",
            data: {"id": obj},
            dataType: "json",
            success: function (val) {
                console.log(val);

                if (val.data == true) {
                    // 删除成功！
                    alert("删除成功！,重新加载当前页面！");
                    window.location.href = "list.html";
                } else {
                    alert("删除失败！");
                }
            }
        });
    }

    // 更新用户播放次数
    function updatePlayCount() {
        if (!currentUser || !currentUser.id) {
            console.log("用户未登录，无法更新播放次数");
            return;
        }

        $.ajax({
            url: "/user/updatePlayCount",
            type: "POST",
            data: JSON.stringify({id: currentUser.id}),
            contentType: "application/json",
            dataType: "json",
            success: function (res) {
                if (res.status === 0) {
                    console.log("播放次数更新成功，当前次数:", res.data.playCount);
                    updatePlayCountDisplay(res.data.playCount);  // 更新显示
                } else {
                    console.log("播放次数更新失败:", res.message);
                }
            },
            error: function (err) {
                console.log("更新播放次数接口调用失败:", err);
            }
        });
    }

    function preservePlayback(event, url) {
        event.preventDefault();
        localStorage.setItem("currentTime", audio.currentTime);
        window.location.href = url;
    }

    // 收藏歌曲
    function loveInfo(obj) {
        $.ajax({
            url: "/lovemusic/likeMusic",
            type: "POST",
            data: {"id": obj},
            dataType: "json",
            success: function (val) {
                if (val.data == true) {
                    alert("收藏成功！");
                    window.location.href = "list.html";
                } else {
                    alert("收藏失败！");
                }
            }
        });
    }

    // 当前播放的音乐列表和索引
    let currentPlaylist = [];
    let currentIndex = -1;
    let isPlaying = false;
    let audio = new Audio(); // 原生Audio对象用于控制播放
    let updateInterval;
    let currentUser = {};

    // 页面加载时获取用户信息
    $(function () {
        $.ajax({
            url: "/api/currentUser",
            type: "POST",
            success: function (data) {
                if (data.status === 0) {
                    currentUser = data.data;
                    console.log("当前用户：", currentUser);
                    updatePlayCountDisplay(currentUser.playCount);  // 更新显示
                } else {
                    console.log("未登录或获取用户信息失败:", data.message);
                }
            },
            error: function (err) {
                console.log("获取用户信息失败:", err);
            }
        });
    });
    // 更新播放次数显示
    function updatePlayCountDisplay(count) {
        $("#playCount").text(count || 0);
    }

    // 修改 playerSong 函数中的时间显示部分
    function playerSong(url, title = "未知标题", singer = "未知歌手", fromList = false) {
        if (!fromList) {
            currentPlaylist = []; // 清空播放列表（如果是从按钮点击进来）
            currentIndex = -1;
        }

        audio.src = url;
        audio.play();
        isPlaying = true;

        // 更新播放次数
        updatePlayCount();

        // 更新UI
        $('#playerTitle').text(title);
        $('#playerArtist').text(singer);
        $('#playIcon').removeClass('fa-play').addClass('fa-pause');

        // 显示播放器
        $('#musicPlayer').removeClass('translate-y-full').addClass('translate-y-0');

        // 添加loadedmetadata事件监听器
        audio.addEventListener('loadedmetadata', function() {
            // 确保duration有值后再显示
            if (!isNaN(audio.duration)) {
                $('#totalTime').text(formatTime(audio.duration));
            }
        });

        // 动态更新进度条
        clearInterval(updateInterval);
        updateInterval = setInterval(() => {
            if (!isNaN(audio.duration)) {
                $('#currentTime').text(formatTime(audio.currentTime));
                $('#progressBar').css("width", (audio.currentTime / audio.duration * 100) + "%");
            }
        }, 500);

        // 保存当前播放状态
        localStorage.setItem("currentSong", JSON.stringify({url, title, singer}));
    }

    // 播放/暂停切换
    $('#playBtn').click(function () {
        if (audio.paused) {
            audio.play();
            $('#playIcon').removeClass('fa-play').addClass('fa-pause');
            $('#musicPlayer').removeClass('translate-y-full').addClass('translate-y-0');
        } else {
            audio.pause();
            $('#playIcon').removeClass('fa-pause').addClass('fa-play');
        }
    });

    // 上一首
    $('#prevBtn').click(function () {
        if (currentPlaylist.length > 0 && currentIndex > 0) {
            currentIndex--;
            const song = currentPlaylist[currentIndex];
            playerSong(song.url, song.title, song.singer, true);
        }
    });

    // 下一首
    $('#nextBtn').click(function () {
        if (currentPlaylist.length > 0 && currentIndex < currentPlaylist.length - 1) {
            currentIndex++;
            const song = currentPlaylist[currentIndex];
            playerSong(song.url, song.title, song.singer, true);
        }
    });

    // 关闭播放器
    $('#closePlayer').click(function () {
        $('#musicPlayer').addClass('translate-y-full').removeClass('translate-y-0');
        audio.pause();
        $('#playIcon').removeClass('fa-pause').addClass('fa-play');
    });

    // 修改格式化时间函数，增加对NaN的处理
    function formatTime(seconds) {
        if (isNaN(seconds)) {
            return "0:00";
        }
        const m = Math.floor(seconds / 60);
        const s = Math.floor(seconds % 60);
        return `${m}:${s.toString().padStart(2, "0")}`;
    }

    // 页面加载后恢复播放状态
    $(function () {
        const song = JSON.parse(localStorage.getItem("currentSong"));
        if (song) {
            playerSong(song.url, song.title, song.singer);
            audio.pause(); // 默认暂停等待用户操作
        }
    });

    // 从列表开始播放
    function startPlayFromList(index, list) {
        currentPlaylist = list.map(item => ({
            url: item.url + ".mp3",
            title: item.title,
            singer: item.singer
        }));
        currentIndex = index;
        const song = currentPlaylist[currentIndex];
        playerSong(song.url, song.title, song.singer, true);
    }
</script>

</body>
</html>